package com.gzz.controller;


import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gzz.common.R;
import com.gzz.pojo.BookPerson;
import com.gzz.pojo.User;
import com.gzz.service.BookPersonService;
import com.gzz.service.UserService;
import com.gzz.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 周佳成
 * @since 2023-11-20
 */
@RestController
@RequestMapping("/api/book/")
public class BookPersonController {
	@Autowired
	BookPersonService bookPersonService;

	@Autowired
	UserService userService;

	@GetMapping("list")
	public R<List<BookPerson>> getBookListByUserId(HttpServletRequest request, HttpServletResponse response){
		String token = request.getHeader("token");
		//获取用户id
		Long id = JWTUtils.parseToken(token);
		User user = userService.getById(id);

		if(user==null){
			response.setStatus(401);
			return R.error("请登录");
		}
		List<BookPerson> list = new ArrayList<>();
		LambdaQueryWrapper<BookPerson> lambdaQueryWrapper = new LambdaQueryWrapper();
		lambdaQueryWrapper.eq(BookPerson::getUserId,id);
		list = bookPersonService.list(lambdaQueryWrapper);

		return R.success(list);

	}

	@PostMapping("add")
	public R<String> addBook(HttpServletRequest request, HttpServletResponse response,@RequestBody BookPerson bookP){
		String token = request.getHeader("token");
		//获取用户id
		Long userId = JWTUtils.parseToken(token);

		Long id = (long) Math.abs(UUID.randomUUID().hashCode());
		if(bookP.getId()!=null){
			bookPersonService.updateById(bookP);
		}else{
			bookP.setId(id);
			bookP.setUserId(userId);
			bookPersonService.save(bookP);
		}

		return R.success("添加成功");
	}
}

